package org.njyinghuo.sdk.bytedance.client.douyin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.njyinghuo.sdk.bytedance.conf.Config;
import org.njyinghuo.sdk.bytedance.exception.DouYinException;

/**
 * @description: 刷新refresh_token
 * @author: Hupengpeng
 * @time: 2021/7/3 11:17
 */
public class OauthRefreshToken {
    private String client_key;
    private String grant_type;
    private String refresh_token;
    private String response;

    public String getClient_key() {
        return client_key;
    }

    public OauthRefreshToken setClient_key(String client_key) {
        this.client_key = client_key;
        return this;
    }

    public String getGrant_type() {
        if (StrUtil.isEmpty(grant_type)) {
            grant_type = "refresh_token";
        }
        return grant_type;
    }

    public OauthRefreshToken setGrant_type(String grant_type) {
        this.grant_type = grant_type;
        return this;
    }

    public String getRefresh_token() {
        return refresh_token;
    }

    public OauthRefreshToken setRefresh_token(String refresh_token) {
        this.refresh_token = refresh_token;
        return this;
    }

    public String getResponse() {
        return response;
    }

    public OauthRefreshToken setResponse(String response) {
        this.response = response;
        return this;
    }

    private OauthRefreshToken() {
    }

    public OauthRefreshToken execute() {
        String url = StrUtil.format("{}{}?client_key={}&grant_type={}&refresh_token={}",
                Config.API_HTTP_SCHEME + Config.API_HOST,
                Config.API_OAUTH_REFRESH_TOKEN,
                getClient_key(),
                getGrant_type(),
                getRefresh_token());
        String rs = HttpUtil.get(url);
        response = rs;
        return this;
    }
    public OauthAccessToken.OauthAccessTokenResponse convert() {
        JSONObject obj = JSONUtil.parseObj(response);
        if ("success".equalsIgnoreCase(obj.getStr("message"))) {
            return JSONUtil.toBean(obj.getJSONObject("data"), OauthAccessToken.OauthAccessTokenResponse.class);
        }
        throw new DouYinException(response);
    }
    protected static OauthRefreshToken New() {
        return new OauthRefreshToken();
    }
}
